#include "path_cache.h"
#include "assert.h"
#include <stdlib.h>
#include <string.h>


typedef struct {
  uint64_t fh;
  object_id id;
} mapping; 


#define MAP_SIZE 1000

static mapping *map;
static uint64_t current;

void init_path_cache () {
  map = malloc (sizeof (mapping) * MAP_SIZE);
  memset (map, 0, sizeof (mapping) * MAP_SIZE);
  current = 1;
}


/* 
  Simply add. Duplicates can happily exist because the same file can
  be opened by different programs 
*/
uint64_t add_mapping (object_id *id) {
  assert (id->ver == 0 && id->dev == 0);
  int i;

  for (i=0; i<MAP_SIZE; i++) {
    mapping *m = map+i;
    if (m->fh == 0) {
      m->fh = current; 
      memcpy (&(m->id), id, sizeof (object_id));
      current++;
      return current-1;
    }
  }

  /* Reach here only if the entire path cache is full */
  assert (0);
}

void resolve_mapping (uint64_t fh, object_id *id) {
  int i;

  for (i=0; i<MAP_SIZE; i++)  {
    mapping *m = map+i;
    if (m->fh == fh) {
      memcpy (id, &(m->id), sizeof (object_id));
      return;
    }
  }
  /* Reach here only if the mapping does not exist, but somebody thinks 
    that it should have existed */
  assert (0);
}

void remove_mapping (uint64_t fh) {
  int i;

  for (i=0; i<MAP_SIZE; i++) {
    mapping *m = map+i;
    if (m->fh == fh) {
      memset (m, 0, sizeof (mapping));
      return;
    }
  }
  /* Reach here only if the mapping does not exist, but somebody thinks
  that it should have existed */
  assert (0);
}

